package com.josn.controller;

import com.josn.interceptors.LoginInterceptor;
import com.josn.pojo.Result;
import com.josn.pojo.User;
import com.josn.service.UserSercice;
import com.josn.utils.JwtUtil;
import com.josn.utils.Md5Util;
import com.josn.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
/**
 * 参数校验注解
 */
@Validated
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserSercice userSercice;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //注册
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$")String username,@Pattern(regexp = "^\\S{5,16}$")String password){
        User u=userSercice.findByUserName(username);
        if (u==null){
            userSercice.add(username,password);
            return Result.success();
        }else {
            return Result.error("用户名已被占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$")String username,@Pattern(regexp = "^\\S{5,16}$")String password){
        User u=userSercice.findByUserName(username);
        //用户名不存在
        if (u==null){
            return Result.error("用户名不存在");
        }
        if (Md5Util.getMD5String(password).equals(u.getPassword())){
            //账号密码正确
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",u.getId());
            claims.put("username",u.getUsername());
            String jwt= JwtUtil.genToken(claims);
            //把token存储到redis中
            ValueOperations<String,String> operations=stringRedisTemplate.opsForValue();
            operations.set(jwt,jwt,1, TimeUnit.HOURS);
            return Result.success(jwt);
        }else {
            //密码错误
            return Result.error("密码错误");
        }
    }

    //获取用户信息
    @GetMapping("/userinfo")
    public User userinfo(){
        Map<String,Object> map=ThreadLocalUtil.get();
        String username=(String) map.get("username");
        ThreadLocalUtil.remove();
        return userSercice.findByUserName(username);
    }

    //更新用户信息
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userSercice.update(user);
        return Result.success();
    }

    //更新用户头像
    @PatchMapping("/updateavatar")
    public Result updateavatar(@RequestParam @URL String avatarurl){
        userSercice.updateavatar(avatarurl);
        return Result.success();
    }

    //更新用户密码
    @PatchMapping("/updatepwd")
    public Result updatepwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        String old_pwd=params.get("old_pwd");
        String new_pwd=params.get("new_pwd");
        String re_pwd=params.get("re_pwd");
        if (!StringUtils.hasLength(old_pwd) || !StringUtils.hasLength(new_pwd) || !StringUtils.hasLength(re_pwd)){
            return Result.error("缺少必要参数");
        }

        //原密码是否正确
        //调用userService根据用户名拿到密码，再和old_pwd进行比较
        Map<String,Object> map=ThreadLocalUtil.get();
        String userName=(String) map.get("username");
        User u=userSercice.findByUserName(userName);
        if (Md5Util.getMD5String(old_pwd).equals(u.getPassword())){
            return Result.error("原密码不正确");
        }

        //new_pwd和re_pwd是否一样
        if (!new_pwd.equals(re_pwd)){
            return Result.error("两次填写的密码不一致");
        }

        //2、调用service完成密码更新
        userSercice.updatepwd(new_pwd);
        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
